package offerv1;

import leetcodev1.链表.Solution;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Offer58_1 {
    public String reverseWords(String s) {
        StringBuffer ans = new StringBuffer();
        StringBuffer tmp = new StringBuffer();
        int n = s.length(), index = n - 1;
        while (index >= 0) {
            if (s.charAt(index) != ' ') {
                tmp.append(s.charAt(index));
            } else if (tmp.length() != 0) {
                if (ans.length() != 0) {
                    ans.append(" ");
                }
                ans.append(tmp.reverse());
                tmp = new StringBuffer();
            }
            index--;
        }

        if (tmp.length() != 0) {
            if (ans.length() != 0) {
                ans.append(" ");
            }
            ans.append(tmp.reverse());
        }
        return ans.toString();
    }

    //正则匹配
    public String reverseWords1(String s) {
        // 除去开头和末尾的空白字符
        s = s.trim();
        // 正则匹配连续的空白字符作为分隔符分割
        List<String> wordList = Arrays.asList(s.split("\\s+"));
        Collections.reverse(wordList);
        return String.join(" ", wordList);
    }

}
